package me.zhengjie.util;

import io.airlift.units.Duration;
import me.zhengjie.service.mapper.QueryMapper;
import static me.zhengjie.util.DbUtil.storeError;

import static java.lang.String.format;

public final class TimeoutUtil {
    private TimeoutUtil() { }

    public static void checkTimeout(QueryMapper queryMapper, Duration queryMaxRunTime, long start, String dataSource, String engine, String queryId, String query, String user) {
        if (System.currentTimeMillis() - start > queryMaxRunTime.toMillis()) {
            String message = format("QueryRecord failed (#%s) in %s: QueryRecord exceeded maximum time limit of %s", queryId, dataSource, queryMaxRunTime.toString());
            storeError(queryMapper, dataSource, engine, queryId, query, user, message);
            throw new RuntimeException(message);
        }
    }
}
